'use strict'
import { Exceptions } from "./../kalend";
import { fsfiles } from "./../middleware/fsFiles";
import config from "./../middleware/config";
import * as Koa from 'koa';
import { prefix, router } from '../middleware/router';
import { response, image } from '../middleware/result';
import * as path from 'path';
import * as fs from 'fs';
import { Tools } from '../kalend';

/** 文件API对象 */
@prefix('file')
class FileuploadController {
    /**
        *
         * @api {POST} /file/upload 图片上传
         * @apiDescription 图片上传
        * @apiGroup file
        * @apiParam {String} data 图片base64位字符串
        * @apiVersion 0.1.0
         *
         */
    @router('/upload', { method: "post" })
    async test(ctx: Koa.Context) {
        // Decoding base-64 image
        // Source: http://stackoverflow.com/questions/20267939/nodejs-write-base64-image-file


        const decodeBase64Image = (dataString: any) => {
            const matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
            const response: any = {};

            if (matches.length !== 3) {
                return new Error('Invalid input string');
            }
            response.type = matches[1];
            response.data = new Buffer(matches[2], 'base64');


            var crypto = require('crypto');
            var seed = crypto.randomBytes(20);
            var uniqueSHA1String = crypto
                .createHash('sha1')
                .update(seed)
                .digest('hex');
            const imageTypeDetected = matches[1].match(/\/(.*?)$/);


            response.name = `${uniqueSHA1String}.${imageTypeDetected[1]}`;
            return response;
        }
        //ctx.request.body.data//
        var base64Data = '';
        var imageBuffer = decodeBase64Image(base64Data);
        var imgtypes = config.get("file")["imgtype"];
        let validataname = Tools.filenamevalidation(imageBuffer.name, imgtypes);
        if (!validataname) {
            Exceptions.known("图片类型异常");
        }
        //验证图片类型；
        const userUploadedImagePath = path.join(process.cwd(), "example.png");// 'file/example.png' ;
        require('fs').writeFile(userUploadedImagePath, imageBuffer.data,
            function () {
                console.log('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath);
            });
        let result1 = await fsfiles.upload({ path: userUploadedImagePath, name: imageBuffer.name });
        fs.unlinkSync(userUploadedImagePath);
        // let result1 = await fsfiles.upload({ path: imageBuffer.data, name: imageBuffer.name });
        response(ctx, result1._id);
    }
    @router('/imgupload', { method: "post" })
    async upload(ctx: Koa.Context) {
        const data = ctx.request.body.file[0];
        const result = await fsfiles.upload({ path: data.path, name: data.name });
        response(ctx, result);
    }

    @router('/uploadfile', { method: "post" })
    async uploadfile(ctx: Koa.Context) {
        const data = ctx.request.body.file[0];
        const result = await fsfiles.upload({ path: data.path, name: data.name });
        response(ctx, result);
    }

    @router('/imgdown/:id')
    async  down(ctx: Koa.Context) {
        var id = ctx.params.id;
        var resultTwo = await fsfiles.getimg(ctx.response, id);
        image(ctx, resultTwo);
    }

    @router('/readStaticFile')
    async  readStaticFile(ctx: Koa.Context) {
        var filename = ctx.query.filename;
        var res = await fsfiles.readStaticFile(ctx, filename);
        response(ctx, res);
    }
    /**
            *
             * @api {POST} /file/wximgupload  微信单个图片上传
             * @apiDescription 图片上传
            * @apiGroup file
            * @apiParam {String} filePath 图片路径（如：http://tmp/wx67d87001fe2776b8.o6zAJsw6Br-TRHEAM03oAQPjhj74.IJvAjzMWWeDf944f2434d64ea152309e7a76cf137ce2.jpg）
            * @apiVersion 0.1.0
             *
             */       
    @router('/wximgupload', { method: 'post' })
    async  wximgupload(ctx: Koa.Context) {
        const data = ctx.request.body.file[0];
        const result = await fsfiles.upload({ path: data.path, name: data.name });
        response(ctx, result);
    }
}